package com.imdroid.lite.net;

import java.io.FileOutputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.json.JSONObject;

import android.util.Log;

import com.imdroid.lite.IMDroid;
import com.imdroid.lite.activities.TeamMapActivity;
import com.imdroid.lite.model.TeamTalk;

/**
 * Handles all the network communications to the wera server.
 */
public class HttpHelper {
	/**
	 * The TAG of the class
	 */
	private final static String TAG = "HttpHelper";

	/**
	 * the server address
	 */
	// public static String ServerAddress =
	// "http://whzb012945.chinaw3.com/webapp/";
	public static String ServerAddress = "http://www.im-droid.com:8080/webapp/";
	public static String FTPAddress = "www.im-droid.com";

	/**
	 * Request a given page with the given parameters, and get the response
	 * message. This method will suppress all exceptions, and when exception
	 * occurs, a string begins with "Error:" will be returned.
	 * 
	 * @param url
	 *            the page name
	 * @param params
	 *            the parameters
	 * @return the response string from server.
	 * @throws Exception
	 */
	public static String execute(String url, List<BasicNameValuePair> params)
			throws Exception {
		// Prepare the connection address
		HttpPost post = new HttpPost(ServerAddress + url);
		HttpEntity entity = null;

		Log.d(TAG, "Request :" + url);

		// Prepare the connection parameters
		if (params != null)
			entity = new UrlEncodedFormEntity(params, "UTF-8");
		HttpClient client = new DefaultHttpClient();
		post.setEntity(entity);

		// Send the request.
		HttpResponse response = client.execute(post);

		if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
			String text = EntityUtils.toString(response.getEntity());
			Log.d(TAG, "response :" + text);
			return text;
		} else {
			throw new Exception("Error:"
					+ EntityUtils.toString(response.getEntity()));

		}
	}

	/**
	 * Request a given page with the given parameters, and get the response
	 * message. This method will suppress all exceptions, and when exception
	 * occurs, a string begins with "Error:" will be returned.
	 * 
	 * @param url
	 *            the page name
	 * @param objectName
	 *            the name of the json object
	 * @param jsonObject
	 *            the name of the json object
	 * @return the response string from server.
	 * @throws Exception
	 */
	public static String execute(String url, String objectName,
			JSONObject jsonObject) throws Exception {
		List<BasicNameValuePair> params = new ArrayList<BasicNameValuePair>();
		params.add(new BasicNameValuePair(objectName, jsonObject.toString()));
		params.add(new BasicNameValuePair("user_id", IMDroid.getUser()
				.getUser_id() + ""));
		return execute(url, params);
	}

	/**
	 * Download file from the server
	 * 
	 * @param targetFile
	 *            the file name
	 * @throws Exception
	 */
	public static void download(TeamTalk tt) throws Exception {
		String target = tt.getFile();
		HttpURLConnection huc = null;
		FileOutputStream fos = null;
		InputStream is = null;
		try {
			System.out.println("开始下载：　" + new Date());
			huc = (HttpURLConnection) (new URL(ServerAddress
					+ "DownloadFile?fileName=" + tt.getFileNameInServer())
					.openConnection());

			fos = new FileOutputStream(target);
			is = huc.getInputStream();
			System.out.println("连接成功：  " + new Date());
			int len = 0;
			byte[] buffer = new byte[4096];
			while ((len = is.read(buffer)) != -1) {
				fos.write(buffer, 0, len);
				fos.flush();
			}

			System.out.println("下载完毕：　" + new Date());

		} catch (Exception e) {
			System.out.println("下载出错：　" + new Date());
			e.printStackTrace();
			throw e;
		} finally {
			if (is != null) {
				try {
					is.close();
				} catch (Exception e) {
				}
			}
			if (fos != null) {
				try {
					fos.close();
					tt.calculateAndSetLength();
					// 插入声音列表
					if (TeamMapActivity.instance != null)
						TeamMapActivity.instance.getTeamTalks().add(tt);
				} catch (Exception e) {
				}
			}
			if (huc != null) {
				try {
					huc.disconnect();
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		}
	}
}
